#include "core/GameManager.h"
#include "util/FPS.h"
#include "component/Doodle.h"
#include "SDL/SDL_mixer.h"

using namespace eats_core;

GameManager::GameManager( int sizeW , int sizeH, GameState * _state)
{
    _running = true;
    _current_state = _state;

    _sizeH = sizeH;
    _sizeW = sizeW;

}

int GameManager::execute()
{
	int state_counter = 0;

	if( _current_state -> setUp() == false ) {
		std::cout << "Não foi possível inicar corretamente o primeiro GameState" << std::endl;
		return -1;
	}

	SDL_Event Event;

	_current_state->state = GameState::running;

	while( _running )
	{

		FPS::FPSControl.update();

		//system("clear");

		while(SDL_PollEvent(&Event)) {
			_current_state->event(&Event);
		}

		if( _current_state->state == GameState::idle )
		{
			continue;
		}

		_current_state->update();

		if( _current_state->state == GameState::finished )
		{

			//FIXME MATAR OS OBEJTOS DESSA FASE AQUI

			//disableComponent(_current_state);
			//_current_state->tearDown();

			state_counter++;
			_current_state = getState(state_counter-1);
			if( _current_state -> setUp() == false ) {
				std::cout << "Não foi possivel trocar o GameStage" << std::endl;
				return -1;
			}
			continue;
		}

		_current_state->render();

	}

	return 0;

}

bool GameManager::disableComponent ( GameState * ref )
{
	vector<GameState *>::iterator iter = statesList.begin();
	for( int i = 0;	iter != statesList.end(); iter++, i++) {
		if( statesList.at(i) == ref ){
			statesList.erase(iter);
			return true;
		}

	}
	return false;
}

bool GameManager::setUp()
{
    return sdlSetUp() && videoSetUp() && audioSetUp() && ttfSetUp();
}

void GameManager::tearDown()
{
	std::cout << "|WARNING| FINALIZANDO CADA ESTAGIO" << std::endl;
    for(unsigned int i = 0; i < statesList.size(); i++)
    {
    	if(statesList.at(i)!= NULL){
    		if( (statesList.at(i) -> state) !=  (GameState::idle) )
        	{
    			std::cout << "|WARNING| FINALIZANDO o ESTAGIO ["<< statesList.at(i)-> _canonical_name << "]"<< std::endl;
            	statesList.at(i) -> tearDown();
            	delete statesList.at(i);
        	}
    	}
    }
    std::cout << "|INFO| Fechando o sound mixer" << std::endl;
    Mix_CloseAudio();
    std::cout << "|INFO| Fechando o ttf" << std::endl;
    TTF_Quit();
    std::cout << "|INFO| Saindo da SDL" << std::endl;
    SDL_Quit();
}


int GameManager::statePush(GameState * state){
    statesList.push_back(state);
    return 0;
}

GameState * GameManager::getState(int x){
    return statesList.at(x);
}

bool GameManager::sdlSetUp()
{
	if(SDL_Init(SDL_INIT_EVERYTHING ) < 0) {
		return false;
	}
	std::cout << "|INFO| SDL iniciada com sucesso. " << std::endl;
	return true;
}

bool GameManager::videoSetUp()
{
	if( SDL_VideoModeOK(_sizeW, _sizeH, 32, SDL_HWSURFACE | SDL_DOUBLEBUF ) == 0 )
	{
		std::cout << "|WARNING| Não é possível iniciar uma janela com as FLAGs sugeridas. Iniciando com as FLAGS padrões." << std::endl;
	}

	if( ( _core_surface = SDL_SetVideoMode( _sizeW, _sizeH , 32, SDL_HWSURFACE | SDL_DOUBLEBUF  )) == NULL) {
		return false;
	}

	//SDL_WM_SetCaption("Attacks", NULL);
	//SDL_WM_SetIcon()


	std::cout << "|INFO| Modulo de video iniciado com sucesso. " << std::endl;
	return true;
}

bool GameManager::audioSetUp()
{
	if( Mix_OpenAudio(22025, MIX_DEFAULT_FORMAT, 2, 4096) == -1){
		std::cout << "|ERROE| Modulo de audio não foi iniciado com sucesso. " << Mix_GetError() << std::endl;
		return false;
	}
	std::cout << "|INFO| Modulo de audio iniciado com sucesso. " << std::endl;
	return true;
}

bool GameManager::ttfSetUp()
{
	if ( TTF_Init() == -1 ){
		std::cout << "|ERROR| Modulo de true type fonte não iniciado. " << std::endl;
		return false;
	}
	std::cout << "|INFO| Modulo de true type fonte iniciado com sucesso. " << std::endl;
	return true;
}

